package service

import (
	"context"
	"errors"

	"gitee.com/daonna/collab-manage-system/ent"
	"gitee.com/daonna/collab-manage-system/ent/user"
	"gitee.com/daonna/collab-manage-system/pkg/util"
	"gitee.com/daonna/collab-manage-system/repository/db"
)

type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

func LoginUser(ctx context.Context, req LoginRequest) (*ent.User, string, string, error) {
	client := db.GetDBClient()
	u, err := client.User().User.Query().Where(user.UsernameEQ(req.Username)).Only(ctx)
	if err != nil {
		return nil, "", "", err
	}

	// Check password (this should be hashed and checked against a hash in a real app)
	if u.Password != req.Password {
		return nil, "", "", errors.New("invalid password")
	}

	// Generate Access JWT token
	accessToken, err := util.GenerateToken(uint(u.ID), u.Username, 1)
	if err != nil {
		return nil, "", "", err
	}

	// Generate Refresh JWT token (with longer expiration)
	refreshToken, err := util.GenerateRefreshToken(uint(u.ID))
	if err != nil {
		return nil, "", "", err
	}

	return u, accessToken, refreshToken, nil
}

type RegisterRequest struct {
	Email    string `json:"email" binding:"required,email"`
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

func RegisterUserByEmail(ctx context.Context, req RegisterRequest) (*ent.User, error) {
	client := db.GetDBClient()
	// 密码应进行哈希处理
	// hashedPassword, err := util.HashPassword(req.Password)
	// if err != nil {
	//     return nil, err
	// }

	u, err := client.User().User.Create().
		SetUsername(req.Username).
		SetPassword(req.Password).
		SetEmail(req.Email).
		Save(ctx)
	if err != nil {
		return nil, err
	}

	// 发送验证邮件逻辑（略）

	return u, nil
}

type PasswordResetRequest struct {
	Email string `json:"email" binding:"required,email"`
}

func ResetPassword(ctx context.Context, req PasswordResetRequest) error {
	client := db.GetDBClient()
	_, err := client.User().User.Query().Where(user.EmailEQ(req.Email)).Only(ctx)
	if err != nil {
		return err
	}

	// 生成密码重置令牌和发送邮件逻辑（略）

	return nil
}

func GetAllUsers(ctx context.Context) ([]*ent.User, error) {
	client := db.GetDBClient()
	users, err := client.User().User.Query().All(ctx)
	if err != nil {
		return nil, err
	}
	return users, nil
}
